package cn.bs.controller;

import ch.qos.logback.core.util.StringUtil;
import cn.bs.domain.dao.Dishes;
import cn.bs.domain.dto.DishDTO;
import cn.bs.domain.pojo.DishesPOJO;
import cn.bs.domain.pojo.Result;
import cn.bs.domain.vo.DishesVO;
import cn.bs.mapper.CanteenMapper;
import cn.bs.mapper.DishesMapper;
import cn.bs.mapper.TypeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/dishes")
public class DishesController {

    @Autowired
    private DishesMapper dishesMapper;

    @Autowired
    private TypeMapper typeMapper;

    @Autowired
    private CanteenMapper canteenMapper;

    /**
     * 获取菜品根据菜品名模糊查询和菜品类型
     * @param
     * @return
     */
    @GetMapping("/getDishes")
    public Result getDishes(@RequestParam(required = false) String type,
                            @RequestParam(required = false) String name) {

        System.out.println("type:" + type + "   name:" + name);

        List<Dishes> dishes = new ArrayList<>();

        if (name == null){
            name = "";
        }

        if (type == null){
            System.out.println("type == null");
            dishes = dishesMapper.getDishesByName(name);
        }else {

            System.out.println("type != null");
            Integer typeId =typeMapper.getTypeId(type);

            if (typeId == null){
                return Result.fail("菜品类型不存在");
            }

            dishes =dishesMapper.getDishesByNameAndType(name, typeId);
        }

        List<DishesPOJO> dishesPOJOs = dishes.stream().map(dish -> {
            DishesPOJO dishesPOJO = new DishesPOJO();
            dishesPOJO.setId(dish.getId());
            dishesPOJO.setCanteenId(dish.getCanteenId());
            String canteenName = canteenMapper.getById(dish.getCanteenId()).getName();
            dishesPOJO.setCanteenName(canteenName);
            String typeName = typeMapper.getTypeName(dish.getTypeId());
            dishesPOJO.setTypeId(dish.getTypeId());
            dishesPOJO.setTypeName(typeName);
            dishesPOJO.setPrice(dish.getPrice());
            dishesPOJO.setDescription(dish.getDescription());
            dishesPOJO.setName(dish.getName());
            dishesPOJO.setImage(dish.getImage());
            return dishesPOJO;
        }).toList();

        DishesVO dishesVO = new DishesVO();
        dishesVO.setDishes(dishesPOJOs);
        dishesVO.setTotal(dishes.size());

        if (dishes.isEmpty()){
            return Result.fail("菜品不存在");
        }

        return Result.ok(dishesVO);
    }

}
